﻿using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class PlayerController : MonoBehaviour
{

    [Header("Player Information")]
    public float moveSpeed = 5.0f;
    [HideInInspector]
    public bool isStartGame = false;
    Transform root;

    [Header("Stick Information")]
    [Tooltip("Stick伸长速度，决定游戏难度")]
    public float stickScaleSpeed = 10f;
    public float stickDownSpeed = 150f;

    [HideInInspector]
    public float stickMaxScale;

    Rigidbody2D rbody;
    Animator animator;
    int groundLayerMask;
    int stickLayerMask;
    bool isReady = false;//是否就位
    GameObject stick = null;
    Vector2 stickPos;
    float score = 0;
    Text scoreText;

    void Start()
    {
        transform.position = new Vector3(1, 5.8f, 0);
        rbody = GetComponent<Rigidbody2D>();
        animator = GetComponent<Animator>();
        scoreText = GameObject.Find("Canvas/ScoreText").GetComponent<Text>();
        root = transform.FindChild("Root");
        groundLayerMask = LayerMask.GetMask("Ground");
        stickLayerMask = LayerMask.GetMask("Stick");
        stickMaxScale = Camera.main.ViewportToWorldPoint(new Vector3(1, 0, 0)).x - transform.position.x;
    }

    void Update()
    {
        if (isReady && isStartGame)
        {
            if (Input.GetMouseButton(0))
            {
                if (stick == null)
                {
                    var obj = Resources.Load("Prefabs/Stick") as GameObject;
                    stick = Instantiate(obj, stickPos, obj.transform.rotation) as GameObject;
                    stick.GetComponent<Rigidbody2D>().isKinematic = true;
                    stick.GetComponent<Collider2D>().isTrigger = true;
                }

                stick.transform.localScale = stick.transform.localScale.y < stickMaxScale ?
                    stick.transform.localScale + Vector3.up * Time.deltaTime * stickScaleSpeed :
                    new Vector3(stick.transform.localScale.x, stickMaxScale, stick.transform.localScale.z);
            }
            else if (Input.GetMouseButtonUp(0))
            {
                //将Stick放倒
                if (stick != null)
                {
                    isReady = false;
                    StartCoroutine(StickDown());
                }
                
            }
        }

        if (Input.GetKeyDown(KeyCode.Escape))
        {
            Application.Quit();
            //scoreText.text = "Android";
        }
    }

    void FixedUpdate()
    {
        var info = Physics2D.Raycast(root.position, Vector2.down, 0.2f, groundLayerMask | stickLayerMask);
        var col = info.collider;
        if (col != null)
        {
            if (col.tag == "Ground")
            {
                var halfSize = col.transform.localScale * 0.5f;
                stickPos = col.transform.position + halfSize;
                stickPos.y = stickPos.y - 0.09f;
                if (col.transform.position.x + halfSize.x - 0.5f > rbody.position.x)
                {
                    animator.SetLayerWeight(1, 1);
                    rbody.MovePosition(rbody.position + Vector2.right * moveSpeed * Time.deltaTime);
                }
                else
                {
                    animator.SetLayerWeight(1, 0);
                    //到达目标点 可以放棍子
                    if (stick == null)
                        isReady = true;
                }
            }
            else if (col.tag == "Stick")
            {
                if (col.transform.position.x + col.transform.localScale.y > rbody.position.x)
                {
                    animator.SetLayerWeight(1, 1);
                    rbody.MovePosition(rbody.position + Vector2.right * moveSpeed * Time.deltaTime);
                }
                else
                {
                    animator.SetLayerWeight(1, 0);
                    col.GetComponent<Rigidbody2D>().isKinematic = false;

                    //检测是否成功登上平台，如果是则加分
                    var exist = Physics2D.Raycast(root.transform.position, Vector2.down, 1.0f, groundLayerMask);

                    if (exist.collider != null)
                    {
                        score++;
                        scoreText.text = string.Format("{0}", score);
                    }

                    stick = null;
                }
            }
        }
        else
        {
            GetComponent<Collider2D>().isTrigger = true;
        }
    }

    IEnumerator StickDown()
    {
        stick.transform.eulerAngles -= new Vector3(0, 0, stickDownSpeed * Time.deltaTime);

        while (stick.transform.eulerAngles.z > 270)
        {
            stick.transform.eulerAngles -= new Vector3(0, 0, stickDownSpeed * Time.deltaTime);
            yield return new WaitForFixedUpdate();
        }

        stick.transform.eulerAngles = new Vector3(0, 0, 270);
        stick.GetComponent<Collider2D>().isTrigger = false;

        //过桥
        yield return MoveToPosition(stickPos.x + 1.0f);
    }

    IEnumerator MoveToPosition(float targetPosX)
    {
        while (transform.position.x < targetPosX)
        {
            if (animator.GetLayerWeight(1) < 1)
                animator.SetLayerWeight(1, 1);

            rbody.MovePosition(transform.position + Vector3.right * moveSpeed * Time.deltaTime);
            yield return new WaitForFixedUpdate();
        }
        animator.SetLayerWeight(1, 0);

        if (stick == null)
            isReady = true;
    }
}
